package cn.kgc.tangcco.anyang.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import cn.hutool.core.util.IdUtil;
import cn.kgc.tangcco.anyang.pojo.User;

@Controller
@SessionAttributes("uuid")
public class LoginController {
	@RequestMapping(value = "/index")
	public String forwordIndexPage() {
		return "/index.jsp";
	}
	@RequestMapping(value = "/login")
	public String login(Model model) {
		model.addAttribute("uuid","2364756237547635453267457632");
		return "/index";
	}
	@RequestMapping(value = "/upload")
	public String upload(Model model,@RequestParam("multipartFile") MultipartFile multipartFile,HttpServletRequest request) {
		// 获取源文件名字 
		String originalFilename = multipartFile.getOriginalFilename();
		System.out.println("源文件名字 >>> " + originalFilename);
		//获得源文件后缀
		String suffix = FilenameUtils.getExtension(originalFilename);
		// int fileSize=500000;
		System.out.println("文件大小: "+multipartFile.getSize());
		String newName = IdUtil.fastSimpleUUID() + "." + suffix;
		System.out.println("新文件名字 >>> " + newName);
		String uploadPath = request.getRealPath("/") + "/statics/upload/";
		File dest = new File(uploadPath ,newName);
		// 文件转换
		try {
			multipartFile.transferTo(dest);
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/index";
	}
	@RequestMapping(value = "/ajax")
	@ResponseBody()
	@CrossOrigin("http://127.0.0.1:5500")
	public User ajax(Model model,User user,HttpSession session) {
		System.out.println("sessionId >>> " + session.getId());
		System.out.println(JSON.toJSONString(user));
		return user;
	}
	@RequestMapping(value = "/ajaxJson")
	@ResponseBody()
	@CrossOrigin("http://127.0.0.1:5500")
	public User ajaxJson(Model model,@RequestBody User user,HttpSession session) {
		System.out.println("sessionId >>> " + session.getId());
		System.out.println(JSON.toJSONString(user));
		return user;
	}
}
